package com.one.blocks.security.authz;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.one.blocks.common.enums.CodeMsgEnum;
import com.one.blocks.common.response.ResponseHelper;
import com.one.blocks.security.enums.SecurityExceptionEnum;
import com.one.blocks.security.exception.AuthzException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * 一般来说异常会被@RestControllerAdvice捕获，所以该类可有可无
 * @author <a href="mailto:idler41@163.con">linfuxin</a> created on 2023-09-24 10:05:15
 */
@Slf4j
public class RestAccessDeniedHandler implements AccessDeniedHandler {

    private final ObjectMapper objectMapper;

    public RestAccessDeniedHandler(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);

        if (log.isDebugEnabled()) {
            log.debug("鉴权失败!", accessDeniedException);
        }
        CodeMsgEnum reason = accessDeniedException instanceof AuthzException ? ((AuthzException) accessDeniedException).getCodeMsgEnum() :
                SecurityExceptionEnum.NO_PERMISSION;
        String resBody = objectMapper.writeValueAsString(ResponseHelper.fail(reason));
        try (PrintWriter printWriter = response.getWriter()) {
            printWriter.print(resBody);
            printWriter.flush();
        }
    }
}
